package com.panda.admin.login.access.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panda.admin.login.dto.RoleDto;
import com.panda.admin.login.dto.RoleMenuDto;
import com.panda.admin.login.entity.SystemRole;
import com.panda.admin.login.entity.SystemRoleMenu;
import com.panda.admin.login.entity.SystemUserRole;
import com.panda.admin.login.access.service.SystemRoleMenuService;
import com.panda.admin.login.access.service.SystemRoleService;
import com.panda.admin.login.access.mapper.SystemRoleMapper;
import com.panda.admin.login.access.service.SystemUserRoleService;
import com.panda.admin.result.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author tucy123
* @description 针对表【system_role(角色表)】的数据库操作Service实现
* @createDate 2023-05-11 13:44:14
*/
@Service
public class SystemRoleServiceImpl extends ServiceImpl<SystemRoleMapper, SystemRole> implements SystemRoleService{

    @Autowired
    SystemUserRoleService systemUserRoleService;

    @Autowired
    SystemRoleMenuService systemRoleMenuService;

    @Autowired
    SystemRoleMapper systemRoleMapper;

    /**
     * 查询全部角色
     * @return
     */
    @Override
    public List<SystemRole> queryAll() {
        return this.lambdaQuery().orderByAsc(SystemRole::getSort).list();
    }

    /**
     * 分页查询角色
     * @param dto
     * @return
     */
    @Override
    public Page<SystemRole> queryRoles(RoleDto dto) {
        Page<SystemRole> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        QueryWrapper<SystemRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(ObjectUtil.isNotEmpty(dto.getRoleName()),"role_name",dto.getRoleName());
        queryWrapper.orderByAsc("sort");
        return systemRoleMapper.selectPage(page,queryWrapper);
    }

    /**
     * 查询角色详情
     * @param roleId
     * @return
     */
    @Override
    public SystemRole queryRoleById(Long roleId) {
        SystemRole systemRole = systemRoleMapper.selectById(roleId);
        List<SystemRoleMenu> roleMenus = systemRoleMenuService.lambdaQuery().eq(SystemRoleMenu::getRoleId, roleId).list();
        List<Long> menuIds = roleMenus.stream().map(SystemRoleMenu::getMenuId).collect(Collectors.toList());
        systemRole.setMenuIds(menuIds);
        return systemRole;
    }

    /**
     * 根据用户id查角色
     * @param userId
     * @return
     */
    @Override
    public SystemUserRole queryById(Long userId) {
        return systemUserRoleService.lambdaQuery().eq(SystemUserRole::getUserId,userId).one();
    }

    /**
     * 增改角色定位
     * @param systemRole
     * @return
     */
    @Override
    public Boolean saveOrUpdateRole(SystemRole systemRole) {
        //权重排序
        if (ObjectUtil.isEmpty(systemRole.getId())){
            Long count = this.count();
            systemRole.setSort(Math.toIntExact(count) + 1);
        }
        //配置菜单
        if(ObjectUtil.isNotEmpty(systemRole.getMenuIds())){
            RoleMenuDto roleMenuDto = new RoleMenuDto();
            roleMenuDto.setRoleId(systemRole.getId());
            roleMenuDto.setMenuIds(systemRole.getMenuIds());
            this.configRoleMenu(roleMenuDto);
        } else {
            //删除角色旧有绑定
            QueryWrapper<SystemRoleMenu> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(SystemRoleMenu::getRoleId,systemRole.getId());
            systemRoleMenuService.remove(wrapper);
        }
        return this.saveOrUpdate(systemRole);
    }

    /**
     * 删除角色
     * @param ids
     * @return
     */
    @Override
    public Boolean deleteRole(List<Long> ids) {
        int i = systemRoleMapper.deleteBatchIds(ids);
        return i != 0;
    }

    /**
     * 角色配置菜单
     * @param dto
     * @return
     */
    @Override
    public Boolean configRoleMenu(RoleMenuDto dto) {
        //删除角色旧有绑定
        QueryWrapper<SystemRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SystemRoleMenu::getRoleId,dto.getRoleId());
        systemRoleMenuService.remove(wrapper);

        //菜单id
        List<Long> menuIds = dto.getMenuIds();
        //保存主体
        List<SystemRoleMenu> roleMenuList = new LinkedList<>();

        for (Long menuId : menuIds) {
            SystemRoleMenu roleMenu = new SystemRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(dto.getRoleId());
            roleMenuList.add(roleMenu);
        }
        return systemRoleMenuService.saveBatch(roleMenuList);
    }

    /**
     * 更改角色权限排序
     * @param id
     * @param direction
     * @return
     */
    @Override
    public Boolean changeSort(Long id, String direction) {
        List<SystemRole> systemRoles = this.list();
        SystemRole activeRole = systemRoles.stream().filter(systemRole -> systemRole.getId().equals(id)).collect(Collectors.toList()).get(0);

        List<Integer> sortList = systemRoles.stream().map(SystemRole::getSort).collect(Collectors.toList());
        Integer sortMin = sortList.stream().min(Integer::compareTo).get();
        Integer sortMax = sortList.stream().max(Integer::compareTo).get();

        Integer oldSort = activeRole.getSort();
        if (direction.equals("asc")){
            if (sortMin.equals(oldSort)){
                throw new ServiceException("最高序列无法升序");
            }
            SystemRole passiveRole = systemRoles.stream().filter(systemRole -> systemRole.getSort().equals(oldSort - 1)).collect(Collectors.toList()).get(0);
            passiveRole.setSort(oldSort);
            activeRole.setSort(oldSort - 1);
            List<SystemRole> roleList = new LinkedList<>();
            roleList.add(passiveRole);
            roleList.add(activeRole);
            return this.updateBatchById(roleList);
        } else {
            if (sortMax.equals(oldSort)){
                throw new ServiceException("最低序列无法降序");
            }
            SystemRole passiveRole = systemRoles.stream().filter(systemRole -> systemRole.getSort().equals(oldSort + 1)).collect(Collectors.toList()).get(0);
            passiveRole.setSort(oldSort);
            activeRole.setSort(oldSort + 1);
            List<SystemRole> roleList = new LinkedList<>();
            roleList.add(passiveRole);
            roleList.add(activeRole);
            return this.updateBatchById(roleList);
        }
    }
}
